package gdut.edu.filter;

import gdut.edu.domain.UserLogin;
import gdut.edu.utils.JwtUtil;
import gdut.edu.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description token认证的过滤器
 * @Author JiaFu
 * @Date 2022/7/5 15:49
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
//            放行
            filterChain.doFilter(request,response);
//            这里需要return防止走完后面的过滤器之后又接着执行下面解析token的代码
            return;
        }
//        解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
//        从redis中获取用户信息
        String redisKey = "login:" + userId;
        UserLogin userLogin = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(userLogin)){
            throw new RuntimeException("用户未登录");
        }
//        将用户信息存入SecurityContextHolder
//        TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userLogin, null, userLogin.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        放行
        filterChain.doFilter(request,response);
    }
}
